const LogsModel = require('../model/logsModel');

const LogsController = {
    /** 获取日志列表 */
    getLogs: async (req, res) => {
        try {
            const filters = {
                op_type: req.query.op_type,
                user_id: req.query.user_id,
                create_time: req.query.create_time,
                op_desc: req.query.op_desc,
                start_time: req.query.start_time,
                end_time: req.query.end_time,
                user_name: req.query.user_name || req.user.username,
            };
            const page = parseInt(req.query.page) || 1;
            const limit = parseInt(req.query.limit) || 10;

            const logs = await LogsModel.getLogs(filters, page, limit);
            res.json({ code: 0, data: logs });
        } catch (err) {
            console.error(err);
            res.status(500).json({ code: 1, msg: '服务器错误' });
        }
    },

    //  添加日志 
    addLog: async (req, res) => {
        try {
            const { op_type, op_desc, ip, user_id, client_type } = req.body;

            // 参数校验
            if (!op_type || !op_desc || !ip) {
                return res.status(400).json({ code: 1, msg: '缺少必要参数' });
            }

            const logId = await LogsModel.createLog({
                op_type,
                op_desc,
                ip,
                user_id,
                client_type
            });

            res.json({ code: 0, msg: '日志添加成功', data: { id: logId } });
        } catch (err) {
            console.error(err);
            res.status(500).json({ code: 1, msg: '服务器错误' });
        }
    },


    // 删除日志（权限校验）
    deleteLog: async (req, res) => {
        try {
            /* 1. 取当前登录用户信息 —— 通过token验证获取 */
            const currentUser = req.user;
            if (!currentUser) {
                return res.status(401).json({ code: 1, msg: '未登录' });
            }

            /* 2. 判断是否为最高权限用户 */
            if (currentUser.role_id !== 1) {
                return res.status(403).json({ code: 1, msg: '无权限删除日志' });
            }

            /* 3. 执行删除 */
            const id = parseInt(req.params.id);
            const rows = await LogsModel.deleteById(id);
            if (rows === 0) {
                return res.status(404).json({ code: 1, msg: '日志不存在' });
            }

            res.json({ code: 0, msg: '删除成功' });
        } catch (err) {
            console.error(err);
            res.status(500).json({ code: 1, msg: '服务器错误' });
        }
    }
}

module.exports = LogsController;